//
//  GuoxueViewController.m
//  GuoxueAppreciate
//
//  Created by 大宝 刘 on 11-11-17.
//  Copyright (c) 2011年 北京帷幄昊合数字娱乐科技有限公司. All rights reserved.
//

#import "GuoxueViewController.h"
#import "ArticleCell.h"

@implementation GuoxueViewController
@synthesize mp3Player = _mp3Player;
@synthesize dataArray = _dataArray;
@synthesize timer = _timer;

@synthesize currentRow = _currentRow;

@synthesize callByDelegate = _callByDelegate;

@synthesize contentTable = _contentTable;
@synthesize descriptionText = _descriptionText;
@synthesize playButton = _playButton;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    [self initMp3Player];
    [self initDataFile];
    
    // 设置表格背景颜色为透明
//    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.contentTable setBackgroundColor:[UIColor clearColor]];
    [self.descriptionText setBackgroundColor:[UIColor clearColor]];
}

- (void)viewDidUnload
{
    [self setDescriptionText:nil];
    [self setContentTable:nil];
    [self setPlayButton:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self initTimer];
    
    self.callByDelegate = NO;
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    // return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
//    if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
//       interfaceOrientation == UIInterfaceOrientationLandscapeRight ) {
//        [self setViewDisplay:NO];
//    } else {
//        [self setViewDisplay:YES];
//    }
    
    return NO;
}

- (void) setViewDisplay:(BOOL)isVerticalFrame {
//    if(isVerticalFrame) {
//        self.contentTable.frame = CGRectMake(0.0, 0.0, 320.0, 300.0);
//        self.descriptionText.frame = CGRectMake(0.0, 300.0, 180.0, 160.0);
//    } else {
//        self.contentTable.frame = CGRectMake(0.0, 0.0, 320.0, 300.0);
//        self.descriptionText.frame = CGRectMake(320.0, 0.0, 160.0, 200.0);
//    }
}

#pragma mark - UITableView delegate methods

// 表格中的区段数量
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

// 区段中的数据行数
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataArray count];
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// TODO 调整表格单元显示
    
    return 60;    
}

// 初始化单元格内容
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellIndentifier = @"cell";
    
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    ArticleCell *cell = (ArticleCell *)[tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    
    if(cell == nil) {
//        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        NSArray *nib = [[NSBundle mainBundle]
                        loadNibNamed:@"ArticleCell" 
                        owner:self options:nil] ;
        
        cell = [nib objectAtIndex:0];
    }
    
    NSDictionary *item = [self.dataArray objectAtIndex:indexPath.row];
    NSString *pinyin = [item objectForKey:@"pinyin"];
    NSString *content = [item objectForKey:@"content"];
    
//    NSLog(@"%@ - %d", content, indexPath.row);
    
    cell.pinyinLabel.text = pinyin;
    cell.contentLabel.text = content;
    
    return cell;
}

// 选中某行
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger row = indexPath.row;
    
    NSLog(@"didSelectRowAtIndexPath row number is  - %d current row is %d", row, self.currentRow);
    
    if(self.currentRow != row) {  
        NSDictionary *item = [self.dataArray objectAtIndex:row];
        
        NSString *description = [item objectForKey:@"description"];
        
        self.descriptionText.text = description;
        
        // 用户手工调整行开始阅读
        if(!self.callByDelegate) {
            NSLog(@"播放行数 - %d", row);
            
            self.mp3Player.currentTime = [[item objectForKey:@"startTime"] intValue];
        }
        
        self.currentRow = row;
    }
}

#pragma mark - 自定义函数

// 初始化三字经音频文件
- (void) initMp3Player {
    
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"szj" ofType:@"mp3"];    
    NSURL *soundUrl = [[NSURL alloc] initFileURLWithPath:soundPath];
    
    self.mp3Player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
    
    [self.mp3Player prepareToPlay];
    self.mp3Player.numberOfLoops = -1;      // 循环播放   
    
    [self.mp3Player play];
}

// 初始化数据文件 
- (void) initDataFile {
    NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"sanzijing" ofType:@"plist"];
    
    self.dataArray = [NSMutableArray arrayWithContentsOfFile:dataPath];
    
    self.currentRow = -1;
}

// 初始化时钟
- (void) initTimer {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:TIME_INTERVAL target:self
                                                selector:@selector(handleTimer) 
                                                userInfo:nil repeats:YES];
}

// 定时器触发处理
- (void) handleTimer {
    
    if(self.mp3Player != nil) {
        // 检测播放器状态，如果没有播放，则开始播放
//        if(!self.mp3Player.playing) {
//            [self.mp3Player play];
//            
//            self.currentRow = -1;
//        } 

        if(self.mp3Player.playing) {
            int currentPlayTime = [self.mp3Player currentTime];
            NSInteger readLine = [self getReadingline:currentPlayTime];
            
//            NSLog(@"handleTimer readLine - %d", readLine);
            
            if(readLine > self.currentRow || readLine == 0) {
                [self doSelectedRow:readLine];
            }    
        }
    } else {
        NSLog(@"播放器错误。");
    }
}

// 获取朗读的行数
- (NSInteger) getReadingline:(NSInteger)currentTime {
    NSInteger result = 0;
    NSInteger currentRow = self.currentRow;
    
    if(currentRow < 0) {
        currentRow = 0;
    }
    
    // 当前行的起始时间
    NSInteger currentStartTime = [[[self.dataArray objectAtIndex:currentRow] objectForKey:@"startTime"] intValue];
    NSInteger totalLines = [self.dataArray count];
    
    if(currentTime >= currentStartTime) {
        NSInteger nextLineStartTime = 0;
        result = currentRow;
        
        // 查找当前时间对应的播放段落
        for(int i = currentRow + 1; i < totalLines; i++) {
            nextLineStartTime = [[[self.dataArray objectAtIndex:i] objectForKey:@"startTime"] intValue];

            if(nextLineStartTime > currentTime) {
                break;
            } else {
                result++;
            }
        }
    }
    
    return result;
}

// 执行选中行
- (void) doSelectedRow:(int)row {
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
    
    [self.contentTable selectRowAtIndexPath:indexPath 
                                   animated:YES 
                             scrollPosition:UITableViewScrollPositionBottom];
    
    self.callByDelegate = YES;
    [[self.contentTable delegate]tableView:self.contentTable 
                   didSelectRowAtIndexPath:indexPath];
    self.callByDelegate = NO;
}

// 播放或暂停
- (IBAction)playOrPause:(id)sender {
    if([self.mp3Player isPlaying]) {
        [self.mp3Player pause];
        [self.playButton setImage:[UIImage imageNamed:@"playbutton.png"] forState:UIControlStateNormal];
        
    } else {
        [self.mp3Player play];
        [self.playButton setImage:[UIImage imageNamed:@"pausebutton.png"] forState:UIControlStateNormal];
    }
}
@end
